/**
 * H5 WebSocket
 */
import { getStore } from '@/libs/cache'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { Notification, MessageBox, Message } from 'element-ui'
import DingdongSound from '@/assets/audio/dingdong.mp3'

/**
 * 连接 Socket
 * 存在跨域问题，需使用域名访问，浏览器上不能使用IP
 */
let stomp
const initWebsocket = () => {
    const user = getStore({ name: 'user' })
    const url = process.env.VUE_APP_BASE_SERVICE_URL+'/websocket'
    
    let sock = new SockJS(url)
    stomp = Stomp.over(sock);
    stomp.debug = false; //调试模式
    stomp.connect({}, function(frame) {
        // console.log('==================== WebSocket 连接成功 ====================')

        //订阅消息(用于连接到WebSocket后返回的消息)
        stomp.subscribe('/notification', function(response) {
            showMessage('success', '', response.body)
        })

        subscribeNtification()
        
        subscribeOneToOne(user.id)
    }, function() {
        console.log('******************** WebSocket 连接失败 ********************')
        showMessage('error', '', 'WebSocket 连接失败')
    });
}

/**
 * 监听订阅广播消息
 */
const subscribeNtification = () => {
    stomp.subscribe('/topic/notification', function(response) {
        const data = JSON.parse(response.body)
        document.getElementById('sound').src = DingdongSound
        showNotification('success', data.title, data.message)
    })
}

/**
 * 监听订阅点对点发送消息
 * @param {用户ID} userId 
 */
const subscribeOneToOne = (userId) => {
    stomp.subscribe('/user/'+userId+'/message', function(response) {
        const data = JSON.parse(response.body)
        document.getElementById('sound').src = DingdongSound

        // if(data.type === 'broadcast' && data.mode === 'Message') {
        //     showMessage('success', data.title, data.message)
        // } else if(data.type === 'broadcast' && data.mode === 'MessageBox') {
        //     showMessageBox('success', data.title, data.message)
        // } else {
        // }
        showNotification('success', data.title, data.message)
    })
}

const showNotification = (type='success', title, message) => {
    let n = Notification({
        type: type,
        duration: 0,
        title: title,
        message: message,
        position: 'bottom-right',
        onClose: () => {
            // 用户点击消息框关闭按钮，异步请求将状态改为已读，暂无法实现
            // 个人用户查看自己的消息，才修改为已读状态，未实现
        }
    })
}

const showMessageBox = (type='success', title, message) => {
    MessageBox({
        type: type,
        title: title,
        message: message,
        customClass: 'errorMessageBox'
    })
}

const showMessage = (type='success', title, message) => {
    Message({
        type: type,
        duration: 2000,
        message: message
    })
}

export default initWebsocket ;